package com.doubao.wechat.config;

import feign.Feign;
import feign.Logger;
import feign.Request;
import feign.Retryer;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClient;
import org.springframework.cloud.loadbalancer.annotation.LoadBalancerClients;
import org.springframework.cloud.openfeign.EnableFeignClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
import org.springframework.web.client.RestTemplate;

import java.util.concurrent.TimeUnit;

/**
 * Feign配置类
 */
@Configuration
@EnableFeignClients(basePackages = {
        "com.doubao.wechat.feign",
        "com.doubao.wechat.client",
        "com.doubao.user.feign"  // 添加这个包，确保 UserFeignClient 被扫描到
})
@LoadBalancerClients({
        @LoadBalancerClient(name = "doubao-user"),
        @LoadBalancerClient(name = "doubao-file")
})
public class FeignConfig {

    /**
     * 配置Feign客户端的日志级别
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        // 可选值: NONE, BASIC, HEADERS, FULL
        return Logger.Level.FULL;
    }

    /**
     * 配置Feign的请求选项，包括超时设置
     */
    @Bean
    public Request.Options options() {
        return new Request.Options(
                10, TimeUnit.SECONDS, // 连接超时
                60, TimeUnit.SECONDS, // 读取超时
                true); // 跟随重定向
    }

    /**
     * 配置Feign的重试策略
     */
    @Bean
    public Retryer feignRetryer() {
        // 第一个参数是初始间隔时间（ms），第二个是最大间隔时间（ms），第三个是最大重试次数
        return new Retryer.Default(100, TimeUnit.SECONDS.toMillis(1), 3);
    }

    /**
     * 配置支持负载均衡的RestTemplate
     */
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    /**
     * 配置Feign，添加降级支持
     */
    @Bean
    @Scope("prototype")
    public Feign.Builder feignBuilder() {
        return Feign.builder();
    }
}